package com.example.controller;

import com.example.entity.User;
import com.example.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {
    
    @Autowired
    private UserRepository userRepository;
    
    // 查询 id 值最大的用户
    @GetMapping("/maxId")
    public User getMaxIdUser() {
        return userRepository.queryAnnotationMaxId();
    }
    
    // 使用占位符参数为 JPQL 语句传递参数值
    @GetMapping("/query")
    public List<User> queryUsers(@RequestParam("username") String username, @RequestParam("phone") String phone) {
        return userRepository.queryAnnotationParam1(username, phone);
    }
    
    // 使用命名参数为 JPQL 语句传递参数值
    @GetMapping("/queryNamed")
    public List<User> queryUsersNamed(@RequestParam("username") String username, @RequestParam("phone") String phone) {
        return userRepository.queryAnnotationParam2(username, phone);
    }
    
    // Spring Data 允许在占位符参数中使用%
    @GetMapping("/queryLike")
    public List<User> queryUsersLike(@RequestParam("username") String username, @RequestParam("phone") String phone) {
        return userRepository.queryAnnotationLikeParam1("%" + username + "%", "%" + phone + "%");
    }
    
    // Spring Data 允许在命名参数中使用%
    @GetMapping("/queryLikeNamed")
    public List<User> queryUsersLikeNamed(@RequestParam("username") String username, @RequestParam("phone") String phone) {
        return userRepository.queryAnnotationLikeParam2("%" + username + "%", "%" + phone + "%");
    }
    
    // 获取用户总数
    @GetMapping("/count")
    public Long getUserCount() {
        return userRepository.getTotalCount();
    }
    
    // 更新用户电话号码
    @PutMapping("/{id}")
    public void updateUserPhone(@PathVariable("id") Integer id, @RequestParam("phone") String phone) {
        userRepository.updateUserPhone(id, phone);
    }
    
    // 插入新用户
    @PostMapping
    public void insertUser(@RequestParam("gender") String gender, @RequestParam("phone") String phone, @RequestParam("username") String username) {
        userRepository.insertUser(gender, phone, username);
    }
}
